package org.example.jimeng;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import com.google.gson.JsonObject;

import java.nio.charset.StandardCharsets;

public class JimengAIClient {
    private static final String API_URL = "https://api.jimeng.ai/generate_image";

    public static String generateImage(String prompt, String apiKey) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_URL);

            // 构建JSON请求体
            JsonObject requestBody = new JsonObject();
            requestBody.addProperty("prompt", prompt);
            requestBody.addProperty("ratio", "16:9");

            // 设置请求头
            httpPost.setHeader("Authorization", "Bearer " + apiKey);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(requestBody.toString(), StandardCharsets.UTF_8));

            // 执行请求并处理响应
            return httpClient.execute(httpPost, response -> {
                int statusCode = response.getCode();
                if (statusCode == 200) {
                    return EntityUtils.toString(response.getEntity());
                } else {
                    throw new RuntimeException("API请求失败，状态码：" + statusCode);
                }
            });
        }
    }


    public static class Main {
        public static void main(String[] args) {
            try {
                String apiKey = "AccessKeyID: AKLTODZhZDAxNWRlMTViNDk4NDk4NDgzYzg5YjQxMWE3MDY\n" +
                        "\n" +
                        "SecretAccessKey: WldGaFpXRXlNelExWlRFNU5HRmlaV0U1TTJKa1lqRTNaalkwWXpGall6TQ==";
                String response = JimengAIClient.generateImage("星空下的城市", apiKey);
                System.out.println("生成结果：" + response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

